package com.atguigu.eduservice.service.impl;

import com.atguigu.commonutils.StatusResult;
import com.atguigu.eduservice.client.OrderClient;
import com.atguigu.eduservice.entity.EduChapter;
import com.atguigu.eduservice.entity.EduCourse;
import com.atguigu.eduservice.entity.EduCourseDescription;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.entity.frontvo.CourseFrontVo;
import com.atguigu.eduservice.entity.frontvo.CourseWebVo;
import com.atguigu.eduservice.entity.vo.CourseInfoVo;
import com.atguigu.eduservice.entity.vo.CoursePublishVo;
import com.atguigu.eduservice.entity.vo.CourseQuery;
import com.atguigu.eduservice.mapper.CourseMapper;
import com.atguigu.eduservice.service.ChapterService;
import com.atguigu.eduservice.service.CourseDescriptionService;
import com.atguigu.eduservice.service.CourseService;
import com.atguigu.eduservice.service.VideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author AIR
 * @since 2022-09-20
 */
@Service
@Transactional
public class CourseServiceImpl extends ServiceImpl<CourseMapper, EduCourse> implements CourseService {

    //课程描述的注入
    @Autowired
    private CourseDescriptionService courseDescriptionService;

    //课程小节的注入
    @Autowired
    private VideoService videoService;

    //课程章节述的注入
    @Autowired
    private ChapterService chapterService;

    @Autowired
    private OrderClient orderClient;


    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        //1 向课程表添加课程基本信息
        //CourseInfoVo对象转换EduCourse
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        int insert = baseMapper.insert(eduCourse);
        if (insert == 0) {
            //添加失败
            throw new GuliException(20001, "添加课程信息失败");
        }

        //添加之后的课程id
        String cid = eduCourse.getId();
        //2 向课程简介添加课程简介
        //EduCourseDescription
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setId(cid);
        eduCourseDescription.setDescription(courseInfoVo.getDescription());
        courseDescriptionService.save(eduCourseDescription);

        return cid;
    }

    //根据课程id查询课程基本信息
    @Override
    public CourseInfoVo getCourseInfo(String courseId) {
        //1查询课程表
        EduCourse eduCourse = baseMapper.selectById(courseId);
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse,courseInfoVo);

        //2查询描述表
        QueryWrapper<EduCourseDescription> wrapper = new QueryWrapper<>();
        wrapper.eq("id",courseId);
        long count = courseDescriptionService.count(wrapper);
        if (count != 0){
            EduCourseDescription courseDescription = courseDescriptionService.getById(courseId);
            courseInfoVo.setDescription(courseDescription.getDescription());
        }
        return courseInfoVo;
    }

    @Override
    public void updateCourseInfo(String courseId, CourseInfoVo courseInfoVo) {
        //修改课程表
        EduCourse eduCourse = new EduCourse();
        courseInfoVo.setId(courseId);
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        int update = baseMapper.updateById(eduCourse);
        if (update == 0){
            throw new GuliException(20001,"修改课程信息失败");
        }

        //修改描述表
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setId(courseId);
        eduCourseDescription.setDescription(courseInfoVo.getDescription());
        courseDescriptionService.updateById(eduCourseDescription);
    }

    //根据课程id查询课程确认信息
    @Override
    public CoursePublishVo getPublishCourse(String courseId) {
        //调用mapper，必须用baseMapper，不能用this
        CoursePublishVo publishCourseInfo = baseMapper.getPublishCourseInfo(courseId);
        return publishCourseInfo;
    }

    @Override
    public void updateStatusById(String courseId) {
        EduCourse eduCourse = new EduCourse();
        eduCourse.setId(courseId);
        eduCourse.setStatus(StatusResult.STATUS_NORMAL.getName());//设置课程发布状态
        baseMapper.updateById(eduCourse);
    }

    @Override
    public void getPublishCourseList(Page pageParam, CourseQuery courseQuery) {
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
//        wrapper.eq("status",StatusResult.STATUS_NORMAL.getName());
        wrapper.orderByDesc("gmt_create");
        if (courseQuery == null){
            baseMapper.selectPage(pageParam,wrapper);
            return;
        }

        if (!StringUtils.isBlank(courseQuery.getStatus())){
            wrapper.eq("status",courseQuery.getStatus());
        }

        if (!StringUtils.isBlank(courseQuery.getTitle())){
            System.out.println(courseQuery.getTitle());
            wrapper.like("title",courseQuery.getTitle());
        }
        if (!StringUtils.isBlank(courseQuery.getTeacherId())){
            System.out.println(courseQuery.getTeacherId());
            wrapper.eq("teacher_id",courseQuery.getTeacherId());
        }
        if (!StringUtils.isBlank(courseQuery.getSubjectParentId())){
            wrapper.eq("subject_parent_id",courseQuery.getSubjectParentId());
        }
        if (!StringUtils.isBlank(courseQuery.getSubjectId())){
            wrapper.eq("subject_id",courseQuery.getSubjectId());
        }

        baseMapper.selectPage(pageParam, wrapper);
    }

    //根据id删除课程列表
    @Override
    public void removeCourse(String courseId) {
        //1 根据课程id删除小节
        videoService.removeVideoByCourseId(courseId);

        //2 根据课程id删除章节
        chapterService.removeChapterByCourseId(courseId);

        //3 根据课程id删除描述
        courseDescriptionService.removeDcByCourseId(courseId);

        //4 根据课程id删除课程本身
        int result = baseMapper.deleteById(courseId);
        if (result == 0){//失败返回
            throw new GuliException(20001,"删除失败");
        }

    }

    @Cacheable(value = "course",key = "'selectHotCourse'")
    //查询前8条热门课程
    @Override
    public List<EduCourse> getHotCourse() {
        //查询前8条热门课程
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        wrapper.last("limit 8");
        List<EduCourse> eduCourses = baseMapper.selectList(wrapper);
        return eduCourses;
    }

    // 课程条件查询带分页
    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> pageParam, CourseFrontVo courseFrontVo) {

        LambdaQueryWrapper<EduCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EduCourse::getStatus,"Normal");

        //判断条件是否为空，不为空拼接
        if (!StringUtils.isBlank(courseFrontVo.getSubjectParentId())){//一级分类
            wrapper.eq(EduCourse::getSubjectParentId,courseFrontVo.getSubjectParentId());
        }

        if (!StringUtils.isBlank(courseFrontVo.getSubjectId())){//二级分类
            wrapper.eq(EduCourse::getSubjectId,courseFrontVo.getSubjectId());
        }

        if (!StringUtils.isBlank(courseFrontVo.getBuyCountSort())){//关注度
            wrapper.orderByDesc(EduCourse::getBuyCount);
        }

        if (!StringUtils.isBlank(courseFrontVo.getGmtCreateSort())){//最新
            wrapper.orderByDesc(EduCourse::getGmtCreate);
        }

        if (!StringUtils.isBlank(courseFrontVo.getPriceSort())){ //价格
            wrapper.orderByDesc(EduCourse::getPrice);
        }


        baseMapper.selectPage(pageParam,wrapper);

        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }

    //根据课程id，编写sql语句查询课程信息
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }


}
